package com.ssms.service;

import com.ssms.commons.Result;
import com.ssms.commons.TablePage;
import com.ssms.dao.ClazzMapper;
import com.ssms.dao.CourseMapper;
import com.ssms.dao.SubjectMapper;
import com.ssms.model.Clazz;
import com.ssms.model.Course;
import com.ssms.model.Course;
import com.ssms.model.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

@Service
public class CourseService {

    @Resource
    private CourseMapper courseMapper;
    @Resource
    private SubjectMapper subjectMapper;
    @Resource
    private ClazzMapper clazzMapper;

    public Result save(Course course) {
        if (check(course)) {
            return Result.failed("课程名称已存在", 500);
        }

        int count = courseMapper.insertSelective(course);
        return count > 0?Result.success():Result.failed("添加失败", 500);
    }


    public TablePage search(TablePage tablePage, Integer subjectId) {
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;
        // 获取分页数据
        List<Course> list = courseMapper.selectPage(start, size, subjectId);
        // 获取符合条件的总数
        int count = courseMapper.selectPageCount(subjectId);
        System.out.println(list);
        tablePage.setCount(count);
        tablePage.setData(list);
        return tablePage;
    }

    public Result update(Course course) {
        if (check(course)) {
            return Result.failed("课程名称已存在", 500);
        }

        int count = courseMapper.updateByPrimaryKeySelective(course);
        return count > 0?Result.success():Result.failed("更新失败", 500);
    }

    private boolean check(Course course){
        int i = courseMapper.checkCourseName(course);
        return i>0;
    }

    // 删除前检查改科目对应的专业下是否存在班级，存在则不能删除科目
    public Result delete(Integer id) {
        Course course = courseMapper.selectByPrimaryKey(id);
        if(course != null){
            Subject subject = subjectMapper.selectByPrimaryKey(course.getSbjId());
            if(subject != null){
                List<Clazz> clazzes = clazzMapper.selectAllBySubjectId(subject.getId());
                if(clazzes != null && clazzes.size() > 0){
                    return Result.failed("该课程已被学生选择，不能删除", 500);
                }
            }
        }
        int count = courseMapper.deleteByPrimaryKey(id);
        return count > 0?Result.success():Result.failed("删除失败", 500);
    }


    public Result getListBySubjectId(Integer subjectId) {
        return Result.success(courseMapper.selectAllBySubjectId(subjectId));
    }
}
